package cn.org.rookie.jeesdp.core.utils;

import cn.org.rookie.jeesdp.core.po.Authority;
import cn.org.rookie.jeesdp.core.po.User;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author LHT
 */

public class SecurityUtils {

    private SecurityUtils() {
    }

    @SuppressWarnings("unchecked")
    public static User getUser() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof Jwt jwt) {
            Map<String, Object> claims = jwt.getClaims();
            return ObjectUtils.populate((Map<String, Object>) claims.get("user"), User.class);
        }
        return null;
    }

    public static String getUserId() {
        return Objects.requireNonNull(getUser()).getId();
    }

    public static String getUsername() {
        return SecurityContextHolder.getContext().getAuthentication().getName();
    }

    public static List<Authority> getAuthorities() {
        return Objects.requireNonNull(getUser()).getAuthorities();
    }

}
